package com.ben.notebook.infrastructure.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * java对象和json字符串的互相转换，使用jackson
 * jackson中日期转换字符串date转localDateTime报错，需自定义反序列化类
 * @date 2020-11-22
 */
public class JsonUtil {

    private final static ObjectMapper MAPPER = new ObjectMapper();

    public static String obj2JsonStr(Object object) throws JsonProcessingException {
        return MAPPER.writeValueAsString(object);
    }

    public static <T> T jsonStr2Obj(String json, Class<T> classType) throws IOException {
        //jackson默认的反序列化类无法解析LocalDateTime，要手动添加指定的反序列化类
        json = json.replaceAll("(\\d{4}-\\d{2}-\\d{2})T", "$1 ");
        SimpleModule deserializer = new SimpleModule().addDeserializer(LocalDateTime.class,
                new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        MAPPER.registerModule(deserializer);
        return MAPPER.readValue(json, classType);
    }

}
